//
//  ComposeViewController.swift
//  mySina
//
//  Created by mac on 15/12/23.
//  Copyright © 2015年 tz. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
    //点击配图按钮的监听
    @objc private func selectPicture() {
//        print(__FUNCTION__)
        //1 隐藏键盘
        textView.resignFirstResponder()
        //2 更新图片选择器的高度
        pictureSelectorVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenH / 3 * 2)
        }
        //强制刷新
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    //Emoji表情
    @objc private func selectEmoticonKeyboard() {
        print(__FUNCTION__)
    }
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func send() {
        //上传文本微博
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showInfoWithStatus("请重新登录", maskType: .Gradient)
            return
        }
        let parameters = ["access_token":token,"status":textView.text ?? ""]
        
        if pictureSelectorVC.imageList.count != 0 {
            //上传图片，字段是pic binary是二进制数据
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //调用上传图片的接口
            let imageData = UIImagePNGRepresentation(pictureSelectorVC.imageList.first!)
            NetwookTools.sharedTools.uploadImage(urlString, parameters: parameters, imageData: imageData!, finished: { (dict, error) -> () in
                self.finishedUpDataStatus(dict, error: error)
            })
        } else {
            //上传文字
            NetwookTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                self.finishedUpDataStatus(dict, error: error)
            }
        }
    }
    private func finishedUpDataStatus(dict:[String : AnyObject]?,error:NSError?) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("网络出错....", maskType: .Gradient)
            return
        }
        SVProgressHUD.showInfoWithStatus("发表微博成功", maskType: .Gradient)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if pictureSelectorVC.imageList.count == 0 {
            //让键盘成为第一响应者
            textView.becomeFirstResponder()
        }
    }

    //懒加载子视图
    private lazy var textView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(18.0)
        tv.backgroundColor = UIColor.greenColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
    }()
    private lazy var placeHolderLabel:UILabel = UILabel(title: "输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18.0)
    //懒加载toolbar
    private lazy var toolBar: UIToolbar = UIToolbar()
    //初始化自定义的对象
    private lazy var pictureSelectorVC:PictureSelectorViewController = PictureSelectorViewController()
    //析构函数(与通知成对存在) -> 此函数只能在类中声明
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
extension ComposeViewController:UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //根据 textView是否有文本，隐藏展位为本，开启发送按钮的交互
        placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension ComposeViewController {
    //更新UI
    private func setupUI() {
        //设置背景色
        view.backgroundColor = UIColor.whiteColor()
        setNavBar()
        setTextView()
        setToolBar()
        setPictureSelectorVC()
        //注册通知
        registerNotification()
    }
    private func setPictureSelectorVC() {
        //首先添加视图控制器
        addChildViewController(pictureSelectorVC)
        //添加视图控制器的根视图
        view.addSubview(pictureSelectorVC.view)
        //将toolbar移到视图的最顶层
        view.bringSubviewToFront(toolBar)
        //设置约束
        pictureSelectorVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    @objc private func keyBoardWillChange(n:NSNotification) {
//        print(n)
        //结构体包装成NSValue  基本类型包装成NSNumber
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let endRect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
//        print(duration,endRect)
        let offsetY = -screenH + endRect.origin.y
        //添加约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //强制刷新 -> 必须放到动画闭包中执行，才会有动画效果
            self.view.layoutIfNeeded()
        }
    }
    //注册通知
    private func registerNotification () {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //设置toolbar
    private func setToolBar() {
        //给toolBar 设置item数组
        var items = [UIBarButtonItem]()
        //想数组中添加元素
        //向数组中添加元素
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        //遍历配置的数组
        for item in itemSettings {
            let imageName = item["imageName"]
            let itenBtn = UIButton(imageName: nil, backImageName: imageName!)
            if let action = item["actionName"] {
                //定义监听事件
                // addTarget可以将字符串,直接转换为 Selector类型.但是,如果传递的是参数,就无法自动包装
                itenBtn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            let barButtonItem = UIBarButtonItem(customView: itenBtn)
            items.append(barButtonItem)
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //移除最后一个弹簧
        items.removeLast()
        toolBar.items = items
        view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self.view)
            make.height.equalTo(44)
        }
    }
    //设置textView
    private func setTextView() {
        //添加子视图
        view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.right.left.equalTo(self.view)
            make.height.equalTo(screenH / 3)
        }
        //给textView添加文本
        textView.addSubview(placeHolderLabel)
        //设置约束
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_right).offset(8)
        }
    }
    //设置导航条
    private func setNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        //默认发送按钮的交互是不允许的
        navigationItem.rightBarButtonItem?.enabled = false
        //自定义textView
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        navigationItem.titleView = titleView
        
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 17.0)
        let namelabel = UILabel(title: UserAccountViewModel().userName ?? "", color: UIColor.darkGrayColor(), fontSize: 14.0)
        //添加子视图
        titleView.addSubview(titleLabel)
        titleView.addSubview(namelabel)
        //添加约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        namelabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
}
